package Producer;

import org.apache.activemq.ActiveMQConnectionFactory;

import javax.jms.*;
import java.util.Random;

public class Publisher {
    private static final String BROKER_URL ="tcp://localhost:61616";


    public static void main(String[] args) {
        ConnectionFactory factory=null;
        Connection connection=null;
        Session session=null;
        MessageProducer producer=null;
        Queue destination=null;
        Topic topic=null;

        try {
            factory = new ActiveMQConnectionFactory(BROKER_URL);
            connection = factory.createConnection();

            session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
//            destination = session.createQueue("TEST");
            topic = session.createTopic("TopicTest");
//            producer = session.createProducer(destination);
            producer = session.createProducer(topic);
            connection.start();

            Message message = null;
            while (true){
                double v = new Random().nextGaussian();
                message = session.createTextMessage(String.valueOf(v));
                producer.send(topic, message);
                System.out.println("Sent a message: "+v);
                Thread.sleep(10);
            }
            // Pause
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if(producer!=null){

                try {
                    if(producer != null)  producer.close();
                    if(session != null) session.close();
                    if(connection != null) connection.close();
                } catch (JMSException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
